package com.mes.eventhandler;

import com.mes.data.EmesTaskSchedulerSource;
import org.apache.commons.lang.StringUtils;
import org.openbravo.base.exception.OBException;
import org.openbravo.base.model.Entity;
import org.openbravo.base.model.ModelProvider;
import org.openbravo.client.kernel.event.EntityNewEvent;
import org.openbravo.client.kernel.event.EntityPersistenceEventObserver;
import org.openbravo.client.kernel.event.EntityUpdateEvent;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.service.OBDal;
import org.openbravo.database.ConnectionProvider;
import org.openbravo.database.SessionInfo;
import org.openbravo.erpCommon.utility.Utility;
import org.openbravo.service.db.DalConnectionProvider;
import javax.enterprise.event.Observes;

/**
 * 任务调度数据源SQL验证
 */
public class EmesTaskSchedulerSourceEventHandler extends EntityPersistenceEventObserver {
	private static Entity[] entities = { ModelProvider.getInstance().getEntity(EmesTaskSchedulerSource.ENTITY_NAME) };

	@Override
	protected Entity[] getObservedEntities() {
		return entities;
	}
	
	public void onUpdate(@Observes EntityUpdateEvent event) throws Throwable {
		if (!isValidEvent(event)) {
			return;
		}
		
		String tabId = SessionInfo.getProcessId();
		
		if(tabId == null){
			return ;
		}
		//判断sql是否正确
		EmesTaskSchedulerSource item = (EmesTaskSchedulerSource) event.getTargetInstance();
		if(StringUtils.isNotEmpty(item.getSql())){
			try {
				OBDal.getInstance().getSession().createSQLQuery(item.getSql()).list();
			} catch (Exception e) {
				String language = OBContext.getOBContext().getLanguage().getLanguage();
		        ConnectionProvider conn = new DalConnectionProvider(false);
				throw new OBException(Utility.messageBD(conn, "sql错误："+e.getMessage(), language));
			}
		}
		
	}
	
	
	public void onSave(@Observes EntityNewEvent event) {
		if (!isValidEvent(event)) {
			return;
		}
		//判断sql是否正确
		EmesTaskSchedulerSource item = (EmesTaskSchedulerSource) event.getTargetInstance();
		if(StringUtils.isNotEmpty(item.getSql())){
			try {
				OBDal.getInstance().getSession().createSQLQuery(item.getSql()).list();
			} catch (Exception e) {
				String language = OBContext.getOBContext().getLanguage().getLanguage();
		        ConnectionProvider conn = new DalConnectionProvider(false);
				throw new OBException(Utility.messageBD(conn, "sql错误："+e.getMessage(), language));
			}
		}
	}
}
